<?php

use console\db\Migration;
use yii\helpers\Json;
use yii\helpers\Console;
use yii\db\Query;
use yii\db\Expression;

/**
 * 格式化图集表
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000007_t_sns_dynamic_gallery_fill extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_gallery}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $this->update($this->tableName, [
            'original' => new Expression('replace(original,"https://img.lnts.cn","")')
        ], ['like', 'original', 'http%', false]);

        $query = (new Query())->from($this->tableName . ' g')->select([
            'g.dynamic_id',
            'd.user_id',
            'd.created_at',
            'd.updated_at',
        ])->where([
            'g.user_id' => 0,
            'g.comment_id' => 0,
        ])
        ->innerJoin('{{%sns_dynamic}} d', 'g.dynamic_id=d.id')
        ->groupBy('g.dynamic_id');
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        foreach ($rows as $row) {
            $migration->db->createCommand()->update($migration->tableName, [
                'user_id' => $row['user_id'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
            ], ['dynamic_id' => $row['dynamic_id']])
            ->execute();
        }
    }

}
